import sys
import os

# Python code to
# demonstrate readlines()
if len(sys.argv)<2:
    print("usage: off2pcd.py <file>")
    sys.exit(1)


off_fn=sys.argv[1]
pcd_fn= os.path.basename(off_fn).split('.')[0]+".pcd"


# Using readlines()
file2 = open(off_fn, 'r')
Lines = file2.readlines()

nvertices=0
nfaces=0
nedges=0

# Strips the newline character

i=1
line=Lines[0]
l=line.strip()
off_seen=False
if l=="OFF":
     lines_fields=3
     n=0
     line=Lines[1]
     l=line.strip()
else:
     lines_fields=4
     i=2
     n=1

parts=l.split(' ')
if len(parts)<lines_fields:
          print("err:line 0")
          print(parts)
          sys.exit(3)
else: 
     if n==1 and parts[0]!="OFF":
              print("OFF not found.")
              sys.exit(2)
     nvertices=int(parts[n])
     n=n+1
     nfaces=int(parts[n])
     n=n+1
     nsdges=int(parts[n])

file1 = open(pcd_fn, 'w')
file1.write("VERSION .7\n")

file1.write("FIELDS x y z\n")
file1.write("SIZE 4 4 4\n")
file1.write("TYPE F F F\n") 
file1.write("COUNT 1 1 1\n")
file1.write("WIDTH %d\n"%(nvertices))
file1.write("HEIGHT 1\n")
file1.write("VIEWPOINT 0 0 0 1 0 0 0\n")
file1.write("POINTS %d\n"%(nvertices))
file1.write("DATA ascii\n")

n=0
while n< nvertices:
    if i>=len(Lines):
        print ("verices not enough:%d,%d "%(n,nvertices))
    line=Lines[i]
    l=line.strip()
    parts=l.split(' ')
    if len(parts)<3:
          print("err:line %d"%i)
          sys.exit(3)
    else: 
          x=float(parts[0])
          y=float(parts[1])
          z=float(parts[2])
          # writing to file
          #L="%f %f %f"%(x,y,z)
          L=l
          file1.writelines("%s\n"%L)
    i=i+1
    n=n+1

file1.close()

